from django.contrib import admin
from django.contrib.auth.admin import UserAdmin as BaseUserAdmin
from django.contrib.auth.admin import GroupAdmin as BaseGroupAdmin
from django.utils.translation import gettext_lazy as _
from django.contrib.auth.models import User, Group

from lib.django.admin import ImportExportFieldUseVerboseNameMixin, ModelAdmin
from import_export.admin import ImportExportModelAdmin
from import_export import resources 

from .models import UserProfile

admin.site.unregister(Group)

from unfold.contrib.import_export.forms import ImportForm, SelectableFieldsExportForm
from unfold.forms import AdminPasswordChangeForm, UserChangeForm, UserCreationForm

class UserProfileResources(ImportExportFieldUseVerboseNameMixin, resources.ModelResource):
    class Meta:
        model = UserProfile


class GroupResources(ImportExportFieldUseVerboseNameMixin, resources.ModelResource):
    class Meta:
        model = Group



@admin.register(UserProfile)
class UserProfileAdmin(BaseUserAdmin, ImportExportModelAdmin, ModelAdmin):
    resource_classes = [UserProfileResources]
    import_form_class = ImportForm
    export_form_class = SelectableFieldsExportForm

    form = UserChangeForm
    add_form = UserCreationForm
    change_password_form = AdminPasswordChangeForm

    list_display = (
        'id', 'username', 'company', 'telephone', 'is_staff', 'date_joined', 'note'
    )
    list_display_links = ('id', 'username')
    # list_filter = ('date_joined', 'is_superuser', 'is_staff')
    search_fields = ('username', 'company')

    fieldsets = (
        (None, {'fields': ('username', 'password')}),
        (_('个人信息'), {'fields': (
            'email', 'company', 'telephone', 'third_app', 'is_researcher', 'bio', 
        )}),
        (_('权限信息'), {'fields': ('is_active', 'is_staff', 'is_superuser', 'groups', 'user_permissions')}),
        (_('重要日期'), {'fields': ('date_joined', 'last_login',)},),
        (_("其他"), { 'fields': ('note',) }),
    )
    ordering = ['date_joined']


@admin.register(Group)
class GroupAdmin(BaseGroupAdmin, ImportExportModelAdmin, ModelAdmin):
    resource_classes = [GroupResources]
    import_form_class = ImportForm
    export_form_class = SelectableFieldsExportForm
